import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../constants/colors.dart';
import '../constants/dimensions.dart';
import 'package:photo_pipeline/photo_pipeline.dart';
import 'base64_cached_image.dart';

/// 图片网格项组件
///
/// 用于在网格中显示单张图片
class PhotoGridItem extends StatelessWidget {
  static final Set<String> _aiDebugLogged = <String>{};

  /// 增强文件数据
  final EnhancedFileInfo file;

  /// 是否选中
  final bool isSelected;

  /// 点击回调
  final VoidCallback onTap;

  /// 选择切换回调
  final VoidCallback onSelectToggle;

  const PhotoGridItem({
    super.key,
    required this.file,
    required this.isSelected,
    required this.onTap,
    required this.onSelectToggle,
  });

  @override
  Widget build(BuildContext context) {
    final aiStatus = file.aiProcessingStatus;
    final logIdentity =
        '${file.fileInfo.id ?? 'null'}-${file.fileInfo.name ?? 'unknown'}';

    assert(() {
      final suffix = aiStatus == null ? 'missing' : 'loaded';
      final logKey = '$logIdentity-$suffix';
      if (!_aiDebugLogged.contains(logKey)) {
        _aiDebugLogged.add(logKey);
        if (aiStatus == null) {
          final resultSummary = file.processingResults
              .map((r) =>
                  '[${r.taskType}] success=${r.success} features=${r.features?.keys.toList() ?? []}')
              .toList();
          debugPrint(
            '[PhotoGridItem] AI score missing for file=$logIdentity '
            'processingResults=${file.processingResults.length} '
            'summary=$resultSummary',
          );
        } else {
          debugPrint(
            '[PhotoGridItem] AI score loaded for file=$logIdentity '
            'overallQuality=${aiStatus.overallQuality.toStringAsFixed(3)} '
            'sharpness=${aiStatus.sharpnessScore.toStringAsFixed(1)} '
            'facialScore=${aiStatus.facialScore.toStringAsFixed(3)} '
            'exposureQuality=${aiStatus.exposureQuality.toStringAsFixed(3)}',
          );
        }
      }
      return true;
    }());

    return GestureDetector(
      onTap: onTap,
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 图片容器
          Container(
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(AppDimensions.radiusSm),
              border: isSelected
                  ? Border.all(
                      color: AppColors.primary,
                      width: 2,
                    )
                  : null,
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(AppDimensions.radiusSm),
              child: _buildThumbnail(),
            ),
          ),

          // 底部文件名和文件大小
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color(0x00000000),
                    Color(0xDD000000),
                  ],
                ),
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(AppDimensions.radiusSm),
                  bottomRight: Radius.circular(AppDimensions.radiusSm),
                ),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 文件名
                  Text(
                    file.fileInfo.name ?? '',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 11,
                      fontWeight: FontWeight.w500,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 2),
                  // 文件大小
                  Text(
                    _formatSize(file.fileInfo.size ?? 0),
                    style: TextStyle(
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 9,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 选择指示器
          Positioned(
            top: 8,
            right: 8,
            child: GestureDetector(
              onTap: onSelectToggle,
              child: Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color: isSelected
                      ? AppColors.primary
                      : Colors.white.withOpacity(0.7),
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: isSelected ? AppColors.primary : Colors.grey,
                    width: 2,
                  ),
                ),
                child: isSelected
                    ? const Icon(
                        Icons.check,
                        size: 16,
                        color: Colors.white,
                      )
                    : null,
              ),
            ),
          ),

          Positioned(
            top: 8,
            left: 8,
            child: _StatusChip(status: file.status),
          ),

          // AI 综合评分（居中显示）
          if (aiStatus != null)
            Positioned.fill(
              child: Center(
                child: Builder(
                  builder: (context) {
                    final score = aiStatus.overallQuality * 100;
                    final color = _getScoreColor(score);
                    return Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.6),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Text(
                        '${score.toStringAsFixed(0)}',
                        style: TextStyle(
                          color: color,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
        ],
      ),
    );
  }

  String _formatSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    }
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  /// 根据分数获取颜色
  /// 90分以上（包含90）：紫色
  /// 75-90：蓝色
  /// 55-75：绿色
  /// 其他：白色
  Color _getScoreColor(double score) {
    if (score >= 90) {
      return Colors.purple;
    } else if (score >= 75) {
      return Colors.blue;
    } else if (score >= 55) {
      return Colors.green;
    } else {
      return Colors.white;
    }
  }

  /// 构建缩略图（带缓存）
  Widget _buildThumbnail() {
    return Base64CachedImage(
      fileInfo: file.fileInfo,
      fit: BoxFit.cover,
      placeholder: _buildGridPlaceholder(showLoader: true),
      errorWidget: _buildGridPlaceholder(isError: true),
    );
  }

  Widget _buildGridPlaceholder(
      {bool isError = false, bool showLoader = false}) {
    Widget child;
    if (showLoader) {
      child = const SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(strokeWidth: 2),
      );
    } else {
      child = Icon(
        isError ? Icons.broken_image_outlined : Icons.image,
        size: 48,
        color: AppColors.textSecondary,
      );
    }

    return Stack(
      fit: StackFit.expand,
      children: [
        Center(child: child),
        Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          child: Container(height: 46),
        ),
      ],
    );
  }
}

class _StatusChip extends StatelessWidget {
  final EnhancedFileInfoStatus status;

  const _StatusChip({required this.status});

  @override
  Widget build(BuildContext context) {
    final color = _statusColor(status);
    final label = _statusLabel(status);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.18),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.4)),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 10,
          fontWeight: FontWeight.w500,
          color: color,
        ),
      ),
    );
  }

  static String _statusLabel(EnhancedFileInfoStatus status) {
    switch (status) {
      case EnhancedFileInfoStatus.none:
        return '未缓存';
      case EnhancedFileInfoStatus.caching:
        return '缓存中';
      case EnhancedFileInfoStatus.cached:
        return '已缓存';
      case EnhancedFileInfoStatus.aiProcessing:
        return 'AI 处理中';
      case EnhancedFileInfoStatus.aiProcessed:
        return 'AI 已完成';
      case EnhancedFileInfoStatus.aiProcessFailed:
        return 'AI 失败';
      case EnhancedFileInfoStatus.aiProcessCancelled:
        return 'AI 已取消';
      case EnhancedFileInfoStatus.uploadPending:
        return '待上传';
      case EnhancedFileInfoStatus.uploading:
        return '上传中';
      case EnhancedFileInfoStatus.uploaded:
        return '已上传';
      case EnhancedFileInfoStatus.uploadFailed:
        return '上传失败';
      case EnhancedFileInfoStatus.uploadCancelled:
        return '上传已取消';
    }
  }

  static Color _statusColor(EnhancedFileInfoStatus status) {
    switch (status) {
      case EnhancedFileInfoStatus.caching:
      case EnhancedFileInfoStatus.uploadPending:
        return AppColors.warning;
      case EnhancedFileInfoStatus.cached:
      case EnhancedFileInfoStatus.uploading:
      case EnhancedFileInfoStatus.aiProcessing:
        return AppColors.info;
      case EnhancedFileInfoStatus.aiProcessed:
      case EnhancedFileInfoStatus.uploaded:
        return AppColors.success;
      case EnhancedFileInfoStatus.aiProcessFailed:
      case EnhancedFileInfoStatus.uploadFailed:
        return AppColors.error;
      case EnhancedFileInfoStatus.aiProcessCancelled:
      case EnhancedFileInfoStatus.uploadCancelled:
        return AppColors.textSecondary;
      case EnhancedFileInfoStatus.none:
        return AppColors.textSecondary;
    }
  }
}
